﻿using Microsoft.AspNetCore.Mvc;
using Sgr.AspNetCore.ActionFilters.AuditLogs;
using Sgr.AspNetCore.ActionFilters.Permissions;
using Sgr.UPMS.Application.Queries;
using Sgr.UPMS.Application.ViewModels;

namespace Sgr.UPMS.Controllers
{
    /// <summary>
    /// 用户权限管理接口
    /// </summary>
    [Route("api/v1/sgr/user-permissions")]
    [ApiController]
    [Produces("application/json")]
    [Tags("User")]
    public class UserPermissionController : ControllerBase
    {
        private readonly IUserPermissionQueries _userPermissionQueries;
        private readonly ICurrentUser _currentUser;
        private readonly ILogger<UserPermissionController> _logger;

        /// <summary>
        /// 初始化用户权限控制器
        /// </summary>
        public UserPermissionController(
            IUserPermissionQueries userPermissionQueries,
            ICurrentUser currentUser,
            ILogger<UserPermissionController> logger)
        {
            _userPermissionQueries = userPermissionQueries ?? throw new ArgumentNullException(nameof(userPermissionQueries));
            _currentUser = currentUser ?? throw new ArgumentNullException(nameof(currentUser));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// 获取当前用户的权限信息
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <response code="200">获取成功</response>
        /// <response code="401">未经授权的访问</response>
        /// <response code="404">指定的用户不存在</response>
        [CheckPermission]
        [HttpGet("info")]
        [ProducesResponseType(typeof(OutUserInfoViewModel), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [AuditLogActionFilter("获取用户权限信息")]
        public async Task<ActionResult<OutUserInfoViewModel>> GetUserPermission(
            CancellationToken cancellationToken = default)
        {
            if (!long.TryParse(_currentUser.Id, out long userId) || !long.TryParse(_currentUser.OrgId, out long orgId))
            {
                return this.CustomBadRequest("无法获取当前用户或组织标识");
            }

            var result = await _userPermissionQueries.GetUserPermissionAsync(
                userId,
                orgId,
                cancellationToken);

            if (result == null)
            {
                _logger.LogInformation("未找到用户 {UserId} 在组织 {OrgId} 的权限信息", userId, orgId);
                return NotFound();
            }

            return Ok(new OutUserInfoViewModel()
            {
                UserName = result.RealName,
                Avatar = "",
                Permissions = result.Permissions.ToArray()
            });
        }

        /// <summary>
        /// 获取用户菜单树
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <response code="200">获取成功</response>
        /// <response code="401">未经授权的访问</response>
        /// <response code="404">指定的用户不存在</response>
        [CheckPermission]
        [HttpGet("menus")]
        [ProducesResponseType(typeof(IEnumerable<OutUserMenuViewModel>), StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [AuditLogActionFilter("获取用户菜单树")]
        public async Task<ActionResult<IEnumerable<OutUserMenuViewModel>>> GetUserMenus(
            CancellationToken cancellationToken = default)
        {
            if (!long.TryParse(_currentUser.Id, out long userId) || !long.TryParse(_currentUser.OrgId, out long orgId))
            {
                return this.CustomBadRequest("无法获取当前用户或组织标识");
            }

            var result = await _userPermissionQueries.GetUserMenusAsync(
                userId,
                orgId,
                cancellationToken);

            if (result == null || !result.Any())
            {
                _logger.LogInformation("No menus found for user {UserId} in organization {OrgId}",
                    userId, orgId);
                return Ok(Array.Empty<OutUserMenuViewModel>());
            }

            return Ok(result);
        }
    }
}